<?php
/*
 * @copyright :     Ienter asia Technologies
 * @author :        Hunglv
 * @version         v.1.0
 * @created         
 * @Description :   Model User
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mmod_user extends MYAD_Model{
protected $table_name = 'm_user';
protected $table_company = 'm_company';
    function __construct(){
        parent::__construct();
    }
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    Get all data for view of User list
     * @Input :         $page = 0;
     * @Output :        (Array) data for view data
     */     
    function getAllData($page = 0){
        $arrayData = array();
        if(isset($_POST['txtName'])||isset($_POST['cboRole'])!=0){
            if($this->input->post('cboRole') != 0){
                if($this->input->post('txtName')!=""){
                    $arrayData = array(
                      'FullName'    => dQuotes($this->input->post('txtName')),
                      'Level'       => $this->input->post('cboRole'),
                    );                     
                }
                else{
                    $arrayData = array(
                      'Level'       => $this->input->post('cboRole'),
                    );                      
                }                      
            }
            else{
                if($this->input->post('txtName')!=""){
                    $arrayData = array(
                      'FullName'    => dQuotes($this->input->post('txtName')),
                    );                      
                }
            }
        }        
        /* load pagination */
        $allUserData = $this->getUserData($arrayData);
        $pagiData = array(
            'base_url'      => base_url('user/'),
            'total_rows'    => count($allUserData['data']),
        );       
        $pagination = $this->config->item('pagination');
        $offset = isset($pagiData['per_page']) ? $pagiData['per_page'] : $pagination['per_page'];
        $pagi = $this->getPagination($pagiData);
        $data = array(
            'show' => 'index',
            'pagi' => $pagi,
            'title' => $this->lang->line('User_title'),
        );            
        /* load user */
        $userData = $this->getUserData($arrayData,$page, $offset);            
        return array_merge($data,$userData,$arrayData); 
    }
    /*
     * @author :        HungLV
     * @Description:    Get User data
     * @Input :         
     *                  (Integer) $limit
     *                  (Integer) $offset
     * @Output :        Array data
     */       
    function getUserData($arrayData,$limit = Null, $offset = Null){                    
        $this->db->from($this->table_name.' as a ');
        $this->db->select('a.FullName,a.Level,a.Email,a.UserId,a.UserName,a.Password,a.Status,a.Del_Flag,a.CompanyCode');
        $this->db->join($this->table_company.' as com ', 'com.CompanyCode = a.CompanyCode');
        $this->db->where('a.CompanyCode',$this->session->userdata('CompanyCode'));
        if(count($arrayData)){
            $this->db->like($arrayData);
        }
        if ($limit !== Null && $offset !== Null) {
            $this->db->limit($offset, $limit);
        } elseif ($limit !== NULL) {
            $this->db->limit($limit);
        }
        $query = $this->db->get();
        $result = $query->result_array();
        return array('data' => $result);
    }
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    check validate form add user
     * @Input :         void
     * @Output :        boolean
     */
    function validate() {
        $_POST['txtFullName'] = mb_convert_kana($_POST['txtFullName'], 'a');
        $_POST['txtUserName'] = mb_convert_kana($_POST['txtUserName'], 'a');        
        $_POST['txtPassword'] = mb_convert_kana($_POST['txtPassword'], 'a');        
        $_POST['txtEmail'] = mb_convert_kana($_POST['txtEmail'], 'a');        
        $_POST['txtDateCreate'] = mb_convert_kana($_POST['txtDateCreate'], 'a');        
        $_POST['txtConfimPassword'] = mb_convert_kana($_POST['txtConfimPassword'], 'a');        
        $this->form_validation->set_error_delimiters('', '');
        $this->form_validation->set_rules('txtFullName', $this->lang->line('User_FullName'), 'trim|required|max_length[255]'); 
        $this->form_validation->set_rules('txtUserName', $this->lang->line('User_UserName'), 'trim|required|max_length[50]|callback_check_UserName[id]|callback_check_space'); 
        $this->form_validation->set_rules('txtPassword', $this->lang->line('User_Pasword'), 'trim|required|min_length[8]|max_length[32]|callback_check_space');
        $this->form_validation->set_rules('txtEmail', $this->lang->line('User_Email'), 'trim|required|valid_email|max_length[255]|callback_check_Email[id]');
        $this->form_validation->set_rules('txtDateCreate', $this->lang->line('User_DateCreate'), 'callback_validate_date');
        $this->form_validation->set_rules('txtConfimPassword', $this->lang->line('User_ConfimPasword'), 'trim|required|min_length[8]|max_length[32]|matches[txtPassword]|callback_check_space');
        $this->form_validation->set_rules('cboLevel', $this->lang->line('User_Manger'), 'callback_select_level');
        return $this->form_validation->run();
    }
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    check validate form edit user
     * @Input :         void
     * @Output :        boolean
     */
    function validate_edit() {
        $_POST['txtFullName'] = mb_convert_kana($_POST['txtFullName'], 'a');
        $_POST['txtUserName'] = mb_convert_kana($_POST['txtUserName'], 'a');        
        $_POST['txtPassword'] = mb_convert_kana($_POST['txtPassword'], 'a');        
        $_POST['txtEmail'] = mb_convert_kana($_POST['txtEmail'], 'a');              
        $_POST['txtConfimPassword'] = mb_convert_kana($_POST['txtConfimPassword'], 'a');        
        $this->form_validation->set_error_delimiters('', '');
        $this->form_validation->set_rules('txtFullName', $this->lang->line('User_FullName'), 'trim|required|max_length[255]'); 
        $this->form_validation->set_rules('txtUserName', $this->lang->line('User_UserName'), 'trim|required|max_length[50]|callback_check_UserName[id]|callback_check_space|xss_clean'); 
        $this->form_validation->set_rules('txtPassword', $this->lang->line('User_Pasword'), 'trim|min_length[8]|max_length[32]|callback_check_space|xss_clean');
        $this->form_validation->set_rules('txtEmail', $this->lang->line('User_Email'), 'trim|required|valid_email|max_length[255]|callback_check_Email[id]|xss_clean');
        $this->form_validation->set_rules('txtConfimPassword', $this->lang->line('User_ConfimPasword'), 'trim|min_length[8]|max_length[32]|matches[txtPassword]|callback_check_space|callback_check_matches[txtPassword]|xss_clean');
        $this->form_validation->set_rules('cboLevel', $this->lang->line('User_Manger'), 'callback_select_level');
        return $this->form_validation->run();
    }    
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    update User
     * @Input :         (Integer) $id
     * @Output :        boolean
     */

    function updateUserData($id=0){
        $data['FullName'] = dQuotes($this->input->post('txtFullName'));
        $data['UserName'] = dQuotes($this->input->post('txtUserName'));
        $data['Email'] = $this->input->post('txtEmail');
        $data['Level'] = $this->input->post('cboLevel');
        $data['DateCreate'] = $this->input->post('txtDateCreate');
        $data['status'] = $this->input->post('chkStatus')?1:0;
        if($id==0){
            $data['Password'] = md5(dQuotes($this->input->post('txtPassword')));
            $data['CompanyCode'] = $this->session->userdata('CompanyCode');
            // insert data to database
            $temp = $this->updateDB($this->table_name,$data);            
        }
        if(is_numeric($id)){
            $data['Upd_ID'] = $this->session->userdata('UserId');
            $data['Upd_Date'] = date('Y-m-d h:i:s');            
            $data['Del_Flag'] = $this->input->post('chkDelFlag');       
            if($this->input->post('txtPassword')){
                $data['Password'] = md5(dQuotes($this->input->post('txtPassword'))); 
            }
            // Update data to database
           $temp = $this->updateDB($this->table_name,$data,array("UserId"=>$id));             
        }
        if ($temp) {
            return array(
                'flag' => TRUE,
                'message' => $this->lang->line('User_updateDB_success')
            );
        } else {
            return array(
                'flag' => FALSE,
                'message' => $this->lang->line('User_updateDB_fall')
            );
        }
    }
    
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    basic data for new add user
     * @Input :         (Interger) $id
     * @Output :        Array
     */

    function getAddUser($id = NULL) {
        /* get user info */
        $userData = $this->getUser($id);
        if ($id && !isset($_POST['btnSubmit']) && $userData) {
            /* is load default */
            if($userData['DateCreate']!='0000-00-00'){
                $dateCrate = date('Y/m/d',strtotime($userData['DateCreate']));
            }
            else{
                $dateCrate = '';
            }
            $temp = array(
                'title'                 => $this->lang->line('User_editUser'),
                'show'                  => 'add_user',
                'js'                    => array('jquery-ui.js'),
                'css'                   => array('jquery-ui.css'),                
                'txtFullName'           => $userData['FullName'],
                'txtUserName'           => $userData['UserName'],
                'txtPassword'           => '',
                'txtConfimPassword'     => '',
                'txtEmail'              => $userData['Email'],
                'cboLevel'              => $userData['Level'],
                'txtDateCreate'         => $dateCrate,
                'chkStatus'             => $userData['Status'],
                'chkDelFlag'             => $userData['Del_Flag'],
                'idUser'                => $userData['UserId'],
            );
        } else {
            $temp = array(
                'title'                 => $this->lang->line('User_AddUser'),
                'show'                  => 'add_user',
                'js'                    => array('jquery-ui.js'),
                'css'                   => array('jquery-ui.css'),
                'txtFullName'           => set_value('txtFullName'),
                'txtUserName'           => set_value('txtUserName'),
                'txtPassword'           => set_value('txtPassword'),
                'txtConfimPassword'     => set_value('txtConfimPassword'),
                'txtEmail'              => set_value('txtEmail'),
                'cboLevel'              => $this->input->post('cboLevel'),
                'txtDateCreate'         => set_value('txtDateCreate')?set_value('txtDateCreate'):date('Y/m/d'),
                'chkStatus'             => $this->input->post('chkStatus'),
                'chkDelFlag'            => $this->input->post('chkDelFlag'),
                'idUser'                => ($userData) ? $id : 0,
            );
        }
        return $temp;
    }

    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    get user
     * @Input :         (Integer) $id
     * @Output :        object/false
     */

    function getUser($id = 0) {
        $this->db->from($this->table_name.' as a ');
        $this->db->select('a.FullName,a.DateCreate,a.Level,a.Email,a.UserId,a.UserName,a.Password,a.Status,a.Del_Flag,a.CompanyCode');
        $this->db->join($this->table_company.' as com ', 'com.CompanyCode = a.CompanyCode');
        $this->db->where('UserId',$id);
        $query = $this->db->get();
        $result = $query->row_array();
        if (count($result)>0) {
            return $result;
        } else {
            return FALSE;
        }
    }
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    get user by input name, value
     * @Input :         $name,$value
     * @Output :        Return array
     */

    function getUserBy($name,$value) {
        $this->db->from($this->table_name.' as a ');
        $this->db->select('a.FullName,a.DateCreate,a.Level,a.Email,a.UserId,a.UserName,a.Password,a.Status,a.Del_Flag,a.CompanyCode');
        $this->db->join($this->table_company.' as com ', 'com.CompanyCode = a.CompanyCode');
        $this->db->where('Del_Flag',0);
        $this->db->where('a.'.$name,$value);
        $query = $this->db->get();
        return $query->row_array();
    }    
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    get count row user by search
     * @Input :         (Array) $arrayData
     * @Output :        Return count
     */    
    function countSearch($arrayData){
        $this->db->from($this->table_name);
        $this->db->like($arrayData);
        $query = $this->db->get();
        return $query->num_rows();
    }
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    get user
     * @Input :         (Integer) $id
     * @Output :        object/false
     */

    function getUserLogin($username,$password,$CompanyCode) {
        $this->db->select('m_user.Password,m_user.Status,m_user.CompanyCode,m_user.FullName,m_user.UserName,m_user.Level,m_user.UserId');
        $this->db->from($this->table_name);
        $this->db->join('m_company', 'm_company.CompanyCode = m_user.CompanyCode');
        $this->db->where('UserName', $username);
        $this->db->where('Password', $password);
        $this->db->where('m_user.CompanyCode', $CompanyCode);
        $this->db->where('m_user.Status', 1);
        $query = $this->db->get();
        $result = $query->row_array();
        return $result;
    }   
}
?>